package com.cloud.pay.payment;

import com.cloud.pay.constant.PayStatusEnum;
import com.cloud.pay.entity.Payment;
import com.cloud.pay.service.PaymentService;
import com.egzosn.pay.ali.api.AliPayService;
import com.egzosn.pay.ali.bean.AliPayMessage;
import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AliPayBackHandler implements PayMessageHandler<AliPayMessage, AliPayService> {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private PayNotifyer payNotifyer;

    /**
     * 支付宝回调的处理
     *
     * @param aliPayMessage 支付消息
     * @param contextMap    上下文
     * @param payService 支付服务
     * @throws PayErrorException 支付错误异常
     */
    @Override
    public PayOutMessage handle(AliPayMessage aliPayMessage, Map<String, Object> contextMap, AliPayService payService) throws PayErrorException {
        Map<String, Object> message = aliPayMessage.getPayMessage();
        String tradeStatus = (String) message.get("trade_status");
        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
            Payment payment = paymentService.getByOrderNo(aliPayMessage.getAppId(), aliPayMessage.getOutTradeNo());
            if (payment != null) {
                payment.setTradeNo(aliPayMessage.getTradeNo());
                payment.setPayStatus(PayStatusEnum.PAID.getCode());
                paymentService.updateById(payment);

                if (payNotifyer.send(payment).successful()) {
                    return payService.getPayOutMessage("success", "ok");
                }
            }
        }
        return payService.getPayOutMessage("fail", "failure");
    }
}
